package liuch.foreach;

import com.sun.xml.internal.ws.server.UnsupportedMediaException;
import org.apache.commons.lang3.ArrayUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;

/**
 * 〈一句话功能简述〉<br>
 * 〈扩展ArrayList实现反序迭代器〉
 *
 * @author 17101651 on 2018/5/17.
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
public class ReversibleArrayList<T> extends ArrayList<T> {

    public ReversibleArrayList(Collection<? extends T> c) {
        super(c);
    }

    public Iterable<T> reversed() {

        return new Iterable<T>() {
            @Override
            public Iterator<T> iterator() {
                return new Iterator<T>() {
                    int current = size() - 1;

                    @Override
                    public boolean hasNext() {
                        return current > -1;
                    }

                    @Override
                    public T next() {
                        return get(current--);
                    }

                    @Override
                    public void remove() {
                        throw new UnsupportedMediaException();
                    }
                };
            }
        };
    }

    public static void main(String[] args) {
        ReversibleArrayList<String> strings = new ReversibleArrayList<String>(Arrays.asList("dsf sdgf dsfg esrgsdr fsdg".split(" ")));
        for (String s : strings) {
            System.out.print(s + " ");
        }
        System.out.println();
        for (String s : strings.reversed()) {
            System.out.print(s + " ");
        }
    }
}
